package com.unitd.base.module.consumer.controller;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qiniu.util.StringUtils;
import com.unitd.base.frame.plugin.module.dto.ResponseUtils;
import com.unitd.base.module.api.entity.*;
import com.unitd.base.module.api.service.*;
import com.unitd.base.module.comm.mybatis.Query;
import com.unitd.base.module.comm.utils.CharUtil;
import com.unitd.base.module.consumer.comm.annotation.IgnoreAuth;
import com.unitd.base.module.consumer.comm.annotation.LoginUser;
import com.unitd.base.module.consumer.comm.controller.ApiBaseAction;
import com.unitd.base.module.consumer.comm.util.ApiPageUtils;
import com.unitd.base.module.master.pojo.dto.CategoryVO;
import com.unitd.base.module.master.pojo.dto.UserVO;
import com.unitd.base.module.master.service.CategoryService;
import com.unitd.base.module.master.service.UserService;
import com.unitd.base.module.shoe.pojo.dto.GoodsVO;
import com.unitd.base.module.shoe.service.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 *
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * 描述: ApiIndexController <br>
 */
@Api(tags = "商品管理")
@RestController
@RequestMapping("/api/goods")
public class ApiGoodsController extends ApiBaseAction {
    @Autowired
    private ApiGoodsService apiGoodsService;
    @Autowired
    private ApiGoodsSpecificationService goodsSpecificationService;
    @Autowired
    private ApiProductService productService;
    @Autowired
    private ApiGoodsGalleryService goodsGalleryService;
    @Autowired
    private ApiGoodsIssueService goodsIssueService;
    @Autowired
    private ApiAttributeService attributeService;
    @Autowired
    private ApiBrandService brandService;
    @Autowired
    private ApiCommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private ApiCommentPictureService commentPictureService;
    @Autowired
    private ApiCollectService collectService;
    @Autowired
    private ApiFootprintService footprintService;
    @Autowired
    private CategoryService apiCategoryService;
    @Autowired
    private ApiSearchHistoryService searchHistoryService;
    @Autowired
    private ApiRelatedGoodsService relatedGoodsService;
    @Autowired
    private ApiCouponService apiCouponService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiCartService cartService;

    @Autowired
    private GoodsService goodsService;

    /**
     *
     */
    @ApiOperation(value = "商品首页")
    @IgnoreAuth
    @PostMapping(value = "index")
    public Object index() {
        Map param = new HashMap();
        param.put("is_delete", 0);
        param.put("is_on_sale", 1);
        List<GoodsVo> goodsList = apiGoodsService.queryList(param);
        return ResponseUtils.toResponsSuccess(goodsList);
    }

    /**
     * 获取商品规格信息，用于购物车编辑时选择规格
     */
    @ApiOperation(value = " 获取商品规格信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "商品id", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping(value = "sku")
    public Object sku(Integer id) {
        Map<String, Object> resultObj = new HashMap();
        //
        Map param = new HashMap();
        param.put("goods_id", id);
        List<GoodsSpecificationVo> goodsSpecificationEntityList = goodsSpecificationService.queryList(param);
        //
        List<ProductVo> productEntityList = productService.queryList(param);
        //
        resultObj.put("specificationList", goodsSpecificationEntityList);
        resultObj.put("productList", productEntityList);
        return ResponseUtils.toResponsSuccess(resultObj);
    }

    /**
     * 商品详情页数据
     */
    @ApiOperation(value = " 商品详情页数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "商品id", paramType = "path", required = true),
            @ApiImplicitParam(name = "referrer", value = "商品referrer", paramType = "path", required = false)})
    @PostMapping(value = "detail")
    public Object detail(String id, Long referrer) {
        Map<String, Object> resultObj = new HashMap();

        Map<String, Object> param = Maps.newHashMap();
        param.put("F3125",id);
        List<GoodsVO> goodsVOList= goodsService.selectByBean(this.getUserDefDbName(),param);
        if(goodsVOList!=null&&!goodsVOList.isEmpty()){
            GoodsVO goodsVO = goodsVOList.get(0);

            resultObj.put("info", goodsVO);

            List<GoodsGalleryVo> gallery = Lists.newArrayList();
            List<Map<String,String>> guigeList = Lists.newArrayList();
            List<Map<String,String>> colorList = Lists.newArrayList();

            param.clear();
            param.put("F3127",goodsVO.getF3127_itemNo());//货号
            param.put("F8500","1");//上架商品
            List<GoodsVO> refGoods= goodsService.selectByBean(this.getUserDefDbName(),param);

            AtomicLong lineNo = new AtomicLong(1);
            refGoods.forEach(refGoodsVo->{

                Arrays.stream(refGoodsVo.getPicUrls()).forEach(e->{
                    GoodsGalleryVo goodsGalleryVo =  new GoodsGalleryVo();
                    goodsGalleryVo.setGoods_id(refGoodsVo.getF3125_goodsNo());
                    goodsGalleryVo.setImg_url(e);
                    gallery.add(goodsGalleryVo);
                });

//                Map<String,String> guige = Maps.newHashMap();
//                guige.put("id",lineNo.get()+"");
//                guige.put("name",refGoodsVo.getF3129_size());
//                guigeList.add(guige);
//
//                Map<String,String> color = Maps.newHashMap();
//                color.put("id",lineNo.get()+"");
//                color.put("name",refGoodsVo.getF3128_color());
//                colorList.add(color);

                Map<String,String> guige = Maps.newHashMap();
                guige.put("id",refGoodsVo.getF3125_goodsNo());
                guige.put("name",refGoodsVo.getF3133());
                guigeList.add(guige);

                lineNo.getAndIncrement();
            });


            resultObj.put("gallery", gallery);
            resultObj.put("guigeList", guigeList);
            resultObj.put("colorList", colorList);
        }
        return ResponseUtils.toResponsSuccess(resultObj);
    }

    /**
     * 　获取分类下的商品
     */
    @ApiOperation(value = " 获取分类下的商品")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "分类id", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping(value = "category")
    public Object category(String f3126_categoryNo) {
        Map<String, Object> resultObj = new HashMap();
        Map<String, Object> params = Maps.newHashMap();
        params.put("F3126",f3126_categoryNo);
        params.put("F8500","1");//上架商品
        List<GoodsVO> goods = goodsService.selectByBean(getUserDefDbName(),params);

        Map<String, List<GoodsVO>> collect = goods.stream().collect(Collectors.groupingBy(GoodsVO::getF3127_itemNo));

        List<GoodsVO> respNewGoods = Lists.newArrayList();

        if(collect!=null&&!collect.isEmpty()){
            collect.forEach((k,v)->{
                GoodsVO goodsVO = v.get(0);
                respNewGoods.add(goodsVO);
            });
        }

        resultObj.put("currentCategory", goods.get(0));
        resultObj.put("goodsList", respNewGoods);
        return ResponseUtils.toResponsSuccess(resultObj);
    }

    /**
     * 　　获取商品列表
     */
    @ApiOperation(value = "获取商品列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "categoryId", value = "分类id", paramType = "path", required = true),
            @ApiImplicitParam(name = "brandId", value = "品牌Id", paramType = "path", required = true),
            @ApiImplicitParam(name = "isNew", value = "新商品", paramType = "path", required = true),
            @ApiImplicitParam(name = "isHot", value = "热卖商品", paramType = "path", required = true)})
    @IgnoreAuth
    @PostMapping(value = "list")
    public Object list(@LoginUser UserVO loginUser, Long categoryId,
                       Integer brandId, String keyword, Integer isNew, Integer isHot,
                       @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size,
                       String sort, String order) {
        Map params = new HashMap();
        params.put("is_delete", 0);
        params.put("is_on_sale", 1);
        params.put("brand_id", brandId);
//        params.put("keyword", keyword);
        params.put("is_new", isNew);
        params.put("is_hot", isHot);
//        params.put("page", page);
//        params.put("limit", size);
//        params.put("order", sort);
//        params.put("sidx", order);
        //
//        if (null != sort && sort.equals("price")) {
//            params.put("sidx", "retail_price");
//            params.put("order", order);
//        } else {
//            params.put("sidx", "id");
//            params.put("order", "desc");
//        }
        //添加到搜索历史
        if (!StringUtils.isNullOrEmpty(keyword)) {
            SearchHistoryVo searchHistoryVo = new SearchHistoryVo();
            searchHistoryVo.setAdd_time(System.currentTimeMillis() / 1000);
            searchHistoryVo.setKeyword(keyword);
            searchHistoryVo.setUser_id(null != loginUser ? loginUser.getUserId().toString() : "");
            searchHistoryVo.setFrom("");
            searchHistoryService.save(searchHistoryVo);

        }
        //筛选的分类
        List<CategoryVO> filterCategory = new ArrayList();
        CategoryVO rootCategory = new CategoryVO();
        rootCategory.setId(0L);
        rootCategory.setName("全部");
        rootCategory.setChecked(false);
        filterCategory.add(rootCategory);

//        params.put("fields", "category_id");
        List<GoodsVo> categoryEntityList = apiGoodsService.queryList(params);
//        params.remove("fields");
        if (null != categoryEntityList && categoryEntityList.size() > 0) {
            List<Integer> categoryIds = new ArrayList();
            for (GoodsVo goodsVo : categoryEntityList) {
                categoryIds.add(goodsVo.getCategoryId());
            }
            //查找二级分类的parent_id
            Map categoryParam = new HashMap();
            categoryParam.put("ids", categoryIds);
//            categoryParam.put("fields", "parent_id");
            List<CategoryVO> parentCategoryList = apiCategoryService.selectByMap(categoryParam);
            //
            List<Long> parentIds = new ArrayList();
            for (CategoryVO categoryEntity : parentCategoryList) {
                parentIds.add(categoryEntity.getParent_id());
            }
            //一级分类
            categoryParam = new HashMap();
//            categoryParam.put("fields", "id,name");
//            categoryParam.put("order", "asc");
//            categoryParam.put("sidx", "sort_order");
            categoryParam.put("ids", parentIds);
            List<CategoryVO> parentCategory = apiCategoryService.selectByMap(categoryParam);
            if (null != parentCategory) {
                filterCategory.addAll(parentCategory);
            }
        }
        //加入分类条件
        if (null != categoryId && categoryId > 0) {
            List<Long> categoryIds = new ArrayList();
            Map categoryParam = new HashMap();
            categoryParam.put("parent_id", categoryId);
//            categoryParam.put("fields", "id");
            List<CategoryVO> childIds = apiCategoryService.selectByMap(categoryParam);
            for (CategoryVO categoryEntity : childIds) {
                categoryIds.add(categoryEntity.getId());
            }
            categoryIds.add(categoryId);
            params.put("categoryIds", categoryIds);
        }
        //查询列表数据
//        params.put("fields", "id, name, list_pic_url, market_price, retail_price, goods_brief");
//        Query query = new Query(params);
//        PageHelper.startPage(query.getPage(), query.getLimit());
        List<GoodsVo> goodsList = apiGoodsService.queryList(params);
        ApiPageUtils goodsData = new ApiPageUtils(new PageInfo(goodsList));
        //搜索到的商品
        for (CategoryVO categoryEntity : filterCategory) {
            if (null != categoryId && (categoryEntity.getId() == 0 || categoryId.equals(categoryEntity.getId()))
                    || null == categoryId && null == categoryEntity.getId()) {
                categoryEntity.setChecked(true);
            } else {
                categoryEntity.setChecked(false);
            }
        }
        goodsData.setFilterCategory(filterCategory);
        goodsData.setGoodsList(goodsList);
        return ResponseUtils.toResponsSuccess(goodsData);
    }

    /**
     * 　　商品列表筛选的分类列表
     */
    @ApiOperation(value = "商品列表筛选的分类列表")
    @IgnoreAuth
    @PostMapping(value = "filter")
    public Object filter(Integer categoryId,
                         String keyword, Integer isNew, Integer isHot) {
        Map params = new HashMap();
        params.put("is_delete", 0);
        params.put("is_on_sale", 1);
        params.put("categoryId", categoryId);
        params.put("keyword", keyword);
        params.put("isNew", isNew);
        params.put("isHot", isHot);
        if (null != categoryId) {
            Map categoryParams = new HashMap();
            categoryParams.put("categoryId", categoryId);
            List<CategoryVO> categoryEntityList = apiCategoryService.selectByMap(categoryParams);
            List<Long> category_ids = new ArrayList();
            for (CategoryVO categoryEntity : categoryEntityList) {
                category_ids.add(categoryEntity.getId());
            }
            params.put("category_id", category_ids);
        }
        //筛选的分类
        List<CategoryVO> filterCategory = Lists.newArrayList();
        CategoryVO rootCategory = new CategoryVO();
        rootCategory.setId(0L);
        rootCategory.setName("全部");
        // 二级分类id
        List<GoodsVo> goodsEntityList = apiGoodsService.queryList(params);
        if (null != goodsEntityList && goodsEntityList.size() > 0) {
            List<Integer> categoryIds = new ArrayList();
            for (GoodsVo goodsEntity : goodsEntityList) {
                categoryIds.add(goodsEntity.getCategoryId());
            }
            //查找二级分类的parent_id
            Map categoryParam = new HashMap();
            categoryParam.put("categoryIds", categoryIds);
            List<CategoryVO> parentCategoryList = apiCategoryService.selectByMap(categoryParam);
            //
            List<Long> parentIds = new ArrayList();
            for (CategoryVO categoryEntity : parentCategoryList) {
                parentIds.add(categoryEntity.getId());
            }
            //一级分类
            categoryParam.put("categoryIds", parentIds);
            List<CategoryVO> parentCategory = apiCategoryService.selectByMap(categoryParam);
            if (null != parentCategory) {
                filterCategory.addAll(parentCategory);
            }
        }
        return ResponseUtils.toResponsSuccess(filterCategory);
    }

    /**
     * 　　新品首发
     */
    @ApiOperation(value = "新品首发")
    @IgnoreAuth
    @PostMapping(value = "new")
    public Object newAction() {
        Map<String, Object> resultObj = new HashMap();
        Map bannerInfo = new HashMap();
        bannerInfo.put("url", "");
        bannerInfo.put("name", "坚持初心，为你寻觅世间好物");
        bannerInfo.put("img_url", "https://platform-wxmall.oss-cn-beijing.aliyuncs.com/upload/20180727/1504208321fef4.png");
        resultObj.put("bannerInfo", bannerInfo);
        return ResponseUtils.toResponsSuccess(resultObj);
    }

    /**
     * 　　人气推荐
     */
    @ApiOperation(value = "人气推荐")
    @IgnoreAuth
    @PostMapping(value = "hot")
    public Object hot() {
        Map<String, Object> resultObj = new HashMap();
        Map bannerInfo = new HashMap();
        bannerInfo.put("url", "");
        bannerInfo.put("name", "大家都在买的严选好物");
        bannerInfo.put("img_url", "https://platform-wxmall.oss-cn-beijing.aliyuncs.com/upload/20180727/1504208321fef4.png");
        resultObj.put("bannerInfo", bannerInfo);
        return ResponseUtils.toResponsSuccess(resultObj);
    }

    /**
     * 　　商品详情页的大家都在看的商品
     */
    @ApiOperation(value = "商品详情页")
    @IgnoreAuth
    @PostMapping(value = "related")
    public Object related(Integer id) {
        Map<String, Object> resultObj = new HashMap();
        Map param = new HashMap();
        param.put("goods_id", id);
//        param.put("fields", "related_goods_id");
        List<RelatedGoodsVo> relatedGoodsEntityList = relatedGoodsService.queryList(param);

        List<Integer> relatedGoodsIds = new ArrayList();
        for (RelatedGoodsVo relatedGoodsEntity : relatedGoodsEntityList) {
            relatedGoodsIds.add(relatedGoodsEntity.getRelated_goods_id());
        }

        List<GoodsVo> relatedGoods = Lists.newArrayList();
        if (null == relatedGoodsIds || relatedGoods.size() < 1) {
            //查找同分类下的商品
            GoodsVo goodsCategory = apiGoodsService.queryObject(id);
            Map paramRelated = new HashMap();
//            paramRelated.put("fields", "id, name, list_pic_url, retail_price");
            paramRelated.put("category_id", goodsCategory.getCategoryId());
//            Query query = new Query(paramRelated);
            relatedGoods = apiGoodsService.queryList(paramRelated);
        } else {
            Map paramRelated = new HashMap();
            paramRelated.put("goods_ids", relatedGoodsIds);
//            paramRelated.put("fields", "id, name, list_pic_url, retail_price");
            relatedGoods = apiGoodsService.queryList(paramRelated);
        }
        resultObj.put("goodsList", relatedGoods);
        return ResponseUtils.toResponsSuccess(resultObj);
    }

    /**
     * 在售的商品总数
     */
    @ApiOperation(value = "在售的商品总数")
    @IgnoreAuth
    @PostMapping(value = "count")
    public Object count() {
        Map<String, Object> resultObj = new HashMap();
        Map param = new HashMap();
        param.put("is_delete", 0);
        param.put("is_on_sale", 1);
        Integer goodsCount = apiGoodsService.queryTotal(param);
        resultObj.put("goodsCount", goodsCount);
        return ResponseUtils.toResponsSuccess(resultObj);
    }

    /**
     * 　　获取商品列表
     */
    @ApiOperation(value = "获取商品列表")
    @IgnoreAuth
    @PostMapping(value = "productlist")
    public Object productlist(Long categoryId,
                              Integer isNew, Integer discount,
                              @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size,
                              String sort, String order) {
        Map params = new HashMap();
        params.put("is_new", isNew);
        params.put("page", page);
        params.put("limit", size);
        params.put("order", sort);
        params.put("sidx", order);
        //
        if (null != sort && sort.equals("price")) {
            params.put("sidx", "retail_price");
            params.put("order", order);
        } else if (null != sort && sort.equals("sell")) {
            params.put("sidx", "orderNum");
            params.put("order", order);
        } else {
            params.put("sidx", "id");
            params.put("order", "desc");
        }
        // 0不限 1特价 2团购
        if (null != discount && discount == 1) {
            params.put("is_hot", 1);
        } else if (null != discount && discount == 2) {
            params.put("is_group", true);
        }
        //加入分类条件
        if (null != categoryId && categoryId > 0) {
            List<Long> categoryIds = new ArrayList();
            Map categoryParam = new HashMap();
            categoryParam.put("parent_id", categoryId);
//            categoryParam.put("fields", "id");
            List<CategoryVO> childIds = apiCategoryService.selectByMap(categoryParam);
            for (CategoryVO categoryEntity : childIds) {
                categoryIds.add(categoryEntity.getId());
            }
            categoryIds.add(categoryId);
            params.put("categoryIds", categoryIds);
        }
        //查询列表数据
        Query query = new Query(params);
        List<GoodsVo> goodsList = apiGoodsService.queryCatalogProductList(query);
        int total = apiGoodsService.queryTotal(query);

        // 当前购物车中
        List<CartVo> cartList = new ArrayList();
        if (null != getUserId()) {
            //查询列表数据
            Map cartParam = new HashMap();
            cartParam.put("user_id", getUserId());
            cartList = cartService.queryList(cartParam);
        }
        if (null != cartList && cartList.size() > 0 && null != goodsList && goodsList.size() > 0) {
            for (GoodsVo goodsVo : goodsList) {
                for (CartVo cartVo : cartList) {
                    if (goodsVo.getId().equals(cartVo.getGoods_id())) {
                        goodsVo.setCart_num(cartVo.getNumber());
                    }
                }
            }
        }
        ApiPageUtils goodsData = new ApiPageUtils(goodsList, total, query.getLimit(), query.getPage());
        goodsData.setGoodsList(goodsData.getData());
        return ResponseUtils.toResponsSuccess(goodsData);
    }
}
